﻿using System;
using System.ComponentModel;
using System.Diagnostics;

namespace ttg_internal.Utilities.Common.Other
{
    /// <summary>
    /// Base class for binding-enabled object
    /// </summary>
    public class BindableObject : INotifyPropertyChanged
    {
        /// <summary>
        /// Initializes a new instance
        /// </summary>
        protected BindableObject()
        {
            //
        }

        public virtual event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Called when a property has changed.
        /// </summary>
        /// <param name="propertyName">The name of the property that has changed.</param>
        protected void Changed(string propertyName)
        {
            if (propertyName != null)
            {
                VerifyPropertyName(propertyName);
            }

            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Warns the developer if this object does not have
        /// a public property with the specified name. This 
        /// method does not exist in a Release build.
        /// </summary>
        [Conditional("DEBUG")]
        [DebuggerStepThrough]
        private void VerifyPropertyName(string propertyName)
        {
            // Verify that the property name matches a real,  
            // public, instance property on this object.
            if (TypeDescriptor.GetProperties(this)[propertyName] == null)
            {
                throw new ArgumentException("Invalid property name: " + propertyName);
            }
        }
    }
}